package com.yukefms.rule.state;

import com.yukefms.engine.running.EventCode;
import com.yukefms.engine.running.RunningContext;
import com.yukefms.engine.running.RunningEvent;
import com.yukefms.jointpoint.BodyPointCloud;
import com.yukefms.rule.interfaces.BARule;
import com.yukefms.rule.interfaces.BAStageRule;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @Description
 * @Author Ping
 * @Date 2021/6/29 10:25
 **/
public class PartialMatchedState extends BARuleState {
    public static Logger logger = LogManager.getLogger(PartialMatchedState.class);

    public PartialMatchedState(final BAStageRule relatedRule) {
        super(relatedRule);
    }

    @Override
    public void doReaction(BodyPointCloud pointCloud, RunningContext context) {
        logger.error("[TRIAL] " + context.getTrialoutCounter().getCurNum()) ;
        context.updateTrialoutCounter();
        if (context.isTrialout()) {
            logger.error("the Rule-{} is FAILED since TRIAL-OUT.", this.relatedRule.ruleName()) ;
            this.relatedRule.setRuleState(RuleStateFlyWeight.getState(RuleStateFlyWeight.FAILED));
            context.notifyRunningEventListener(EventCode.FAILED,
                                                   this.relatedRule.ruleName(),
                                                   this.relatedRule.getInvariantViolatedDesc());
            // reaction on the fail and stop the reaction.
            this.relatedRule.doReaction(pointCloud, context);

        } else {
            // trial it again.
           /*  logger.error("the Rule-{} is PARTIAL_MATCHED and RESET.", this.relatedRule.ruleName()) ;
            context.resetTimer();
            context.resetInputErrorCounter();
            context.resetInvariantFailCounter();
            this.relatedRule.setRuleState(RuleStateFlyWeight.getState(RuleStateFlyWeight.IN_ACTIVATED));*/
            // reset the rule to the first stage.
            // trial it again.
            relatedRule.redo() ;
            logger.error("[TRIAL] {}: the Rule was RESET. ",context.getTrialoutCounter().getCurNum() ) ;
            logger.error("Current Stage {}. ", this.relatedRule.currentStage().getName() ) ;
            context.resetTimer();
            context.resetInputErrorCounter();
            context.resetInvariantFailCounter();
            this.relatedRule.setRuleState(RuleStateFlyWeight.getState(RuleStateFlyWeight.IN_ACTIVATED));


        }
        // empty caching structure
        context.resetCachingStructure();

    }

}
